package com.beeasy.hzbpm.ctrl;

import cn.hutool.core.util.IdUtil;
import com.github.llyb120.nami.ctrl.Ctrl;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Obj;
import com.mongodb.client.model.UpdateOptions;

import static com.beeasy.hzbpm.bean.MongoService.db;
import static com.github.llyb120.json.Json.a;
import static com.github.llyb120.json.Json.o;

public class role extends Ctrl {

    static String tempDir = System.getProperty("java.io.tmpdir");

    public Arr list() {
        return db.getCollection("role")
            .aggregate(a(
                o("$sort", o("sort", 1)),
                o("$project",o(
                    "_id", 0
                ))
            ).toBson())
            .into(a());
    }

    public Object getUsers() {
        Arr users = db.getCollection("user")
            .aggregate(a(
                o("$match", o(
                    "orgs", o(
                        "$elemMatch", o(
                            "id", $get.s("id"),
                            "type", "ROLE"
                        )
                    )
                )),
                o("$project", o(
                    "type", "USER",
                    "uid", "$id",
                    "_id", 0,
                    "name", o(
                        "$concat", a("$true_name", "(", "$username", ")")
                    )
                ))
            ).toBson())
            .into(a());
        return o(
            "USER", users
        );

//        List<Obj> users = sqlManager.execute(new SQLReady("select distinct uid, u.true_name || '(' || u.username || ')' as name,'USER' as type from t_user_org ud inner join t_user u on ud.uid = u.id where ud.oid = ?", $get.s("id")), Obj.class);

    }

    /**
     * 从角色移除用户
     */
    public void delUser(){
        db.getCollection("user")
            .updateOne(
                o(
                    "id", $request.s("uid")
                ).toBson(),
                o(
                    "$pull", o(
                        "orgs", o(
                                "id", $request.s("oid"),
                                "type", "ROLE"
                        )
                    )
                ).toBson()
            );
    }

    /**
     * 给角色添加用户
     */
    public void addUser(){
        db.getCollection("user")
            .updateOne(
                o(
                    "id", $request.s("uid"),
                    "orgs", o(
                        "$not", o(
                            "$elemMatch", o(
                                "id", $request.s("oid"),
                                "type", "ROLE"//($request.s("type"))
                            )
                        )
                    )
                ).toBson(),
                o(
                    "$push", o(
                        "orgs", o(
                            "id", $request.s("oid"),
                            "type", "ROLE"//($request.s("type"))
                        )
                    )
                ).toBson()
            );
    }

    public void del(){
        //删除角色
        db.getCollection("role")
            .deleteOne(o(
                "id", $request.s("id")
            ).toBson());
        //删除用户归属
        db.getCollection("user")
            .updateMany(
                o(
                    "orgs", o("$elemMatch", o(
                        "id", $request.s("id"),
                        "type", "ROLE"
                    ))
                ).toBson(),
                o(
                    "$pull", o(
                        "orgs", o(
                            "id", $request.s("id"),
                            "type", "ROLE"
                        )
                    )
                ).toBson()
            );
    }


    public void save(){
        String id = $post.s("id", "");
        String name = $request.ss("name").trim();
        if(name.isEmpty()){
            error("角色名不能为空");
        }
        $post.ii("sort");
        Obj doc = o(
            "id", id,
            "name", name,
            "sort", $post.ii("sort"),
            "pid", $request.get("parent_id")
//            "parent_id", $request.get("parent_id"),
//            "type", type(),
//            "tag_info", $post.aa("tag_info")
        );
        if(id.isEmpty()){
            //同目录下不能有相同的
            long count = db.getCollection("role")
                .count(o(
                    "name", name,
                    "pid",$request.get("pid")
                ).toBson());
            if(count > 0){
                error("已经有同名角色" );
            }
            doc.put("id", IdUtil.objectId());
        } else {
            long count = db.getCollection("role")
                .count(o(
                    "name", name,
                    "pid", $request.get("pid"),
                    "id", o("$ne", id)
                ).toBson());
            if(count > 0){
                error("已经有同名角色" );
            }
        }
        db.getCollection("role")
            .replaceOne(o("id", doc.ss("id")).toBson(), doc.toBson(), new UpdateOptions().upsert(true));
    }



    /**
     * 导出
     * @return
     */
//    public MultipartFile export(){
//        File temp = new File(tempDir, StrUtil.uuid() + ".xlsx");
//        ExcelWriter writer = new ExcelWriter(temp);
//        String[] columns = {"角色名称", "角色排序", "是否全局角色"};
//        writer.setColumnWidth(0, 50);
//        for (int i = 0; i < columns.length; i++) {
//            writer.writeCellValue(i, 0, columns[i]);
//        }
//        Arr list = list();
//        int i = 1;
//        for (Obj obj : list.oa()) {
//            writer.writeCellValue(0, i, obj.s("name"));
//            writer.writeCellValue(1, i, obj.ii("sort"));
//            writer.writeCellValue(2, i, "1");
//            i++;
//        }
//        writer.flush(temp);
//        writer.close();
//        return new MultipartFile("角色导出" + DateUtil.formatDate(new Date()) + ".xlsx", temp, true);
//    }

    /**
     * 导入
     * @return
     */
//    public void imt(MultipartFile file) throws IOException {
//        byte[] bs = file.getBytes();;
//        ExcelReader reader = ExcelUtil.getReader(new ByteArrayInputStream(bs));
//        List<Map<String, Object>> list = reader.readAll();
//        List<Object> head = reader.readRow(0);
//        if(head.size() != 3){
//            error("导入失败");
//        }
//        Arr newlist = aaa(list.stream()
//            .map(Json::ooo)
//            .map(e -> {
//                return o(
//                    "id", IdUtil.objectId(),
//                    "parent_id", null,
//                    "type", "ROLE",
//                    "sort", e.ii((String) head.get(1)),
//                    "tag_info", a(),
//                    "name", e.ss((String) head.get(0)).trim()
//                );
//            })
//            .filter(e -> e.ss("name").isEmpty())
//            .collect(Collectors.toList()));
//        if(!newlist.isEmpty()){
//            //清空角色
//            db.getCollection("org").deleteMany(o(
//                "type", type()
//            ).toBson());
//            //清空所有用户持有的角色
//            db.getCollection("user")
//                .updateMany(o().toBson(), o(
//                    "$pull", o(
//                        "orgs", o(
//                            "type", type()
//                        )
//                    )
//                ).toBson());
//            //插入新角色
//            db.getCollection("org").insertMany(newlist.toBson());
//        }
//    }
    

}
